#include "../../include/OrderHandler.hpp"
#include "../../include/AuthHandler.hpp"

// 基类  构造函数初始化基类ApiHandler
OrderHandler::OrderHandler(DatabasePool& pool) : ApiHandler(pool) {}
// 处理订单
void OrderHandler::createOrder(const Request& req, Response& res) {
	// 抓异常
	try {
		// 认证用户登录状态并获取用户ID和角色
        int userId;
        string role;
		// 没登陆的就弹异常 然后回滚
		if (!AuthHandler::authenticateRequest(req, userId, role)) {
			// 给状态码 401 对应未登录
			return sendError(res, "需要登录", 401);
		}
		// 登录的就验证 请求的参数 及对应字段
		Value params = parseRequest(req);
		// 需要的参数 用可变参数列表 放进vector来存储
		vector<string> required = {"item", "delivery_address", "contact_phone"};
		// 都先考虑错误的情况 给对应的异常状态码
		if (!validateParams(params, required)) 
			return sendError(res, "缺少必要的订单信息", 400);
		// 事务类来执行 sql 操作 
		withTransaction([&](DBUtil::Transaction& trans) {
			// 计算订单总金额
			Value& items = params["items"];
			double totalAmount = 0.0;		// 怕隐式转成INT 了
			// 遍历菜单 查询价格给总金额
			for (auto& item : items) {
				Value dishAns = trans.query("SELECT price FROM dishes WHERE id = " + to_string(item["dish_id"].asInt()));
				// 菜品不存在的情况
				if (dishAns.empty() || !dishAns.isArray() || dishAns.size() == 0)
					throw runtime_error("菜品ID: " + to_string(item["dish_id"].asInt()) + "不存在");
				// 累加算总金额
				double price = dishAns[0]["price"].asDouble();
				int quantity = item["quantity"].asInt();
				totalAmount += price * quantity;
			}
			// 价格算出来了就放进订单里面
			string orderSql = "INSERT INTO orders (user_id, status_id, total_amount, "
                            "delivery_address, contact_phone) VALUES (" +
                            to_string(userId) + ", 1, " + // 默认状态为1（待处理）
                            to_string(totalAmount) + ", '" +
                            params["delivery_address"].asString() + "', '" +
                            params["contact_phone"].asString() + "')";
			// 插入订单
			int affected = trans.execute(orderSql);
			if (affected <= 0)		throw runtime_error("创建订单失败");
			// 获取刚插入的Id
			Value orderIdAns = trans.query("SELECT LAST_INSERT_ID() as id");
			if (orderIdAns.empty())		throw runtime_error("无法获取订单ID");
			int orderId = orderIdAns[0]["id"].asInt();
			// 明细记录
			for (auto& item : items) {
				string itemSql = "INSERT INTO order_items (order_id, dish_id, quantity, price) " "VALUES (" + to_string(orderId) + ", " + to_string(item["dish_id"].asInt()) + ", " + to_string(item["quantity"].asInt()) + ", " + "(SELECT price FROM dishes WHERE id = " + to_string(item["dish_id"].asInt()) + "))";
				trans.execute(itemSql);
			}
			// 给响应 
			Value response;
			response["order_id"] = orderId;
			response["total_amount"] = totalAmount;
			response["message"] = "订单创建成功";
			sendSucess(res, response, 201);		// 返回201状态码表示成功创建订单
		});
	} catch (const exception& e) {
		sendError(res, e.what());
	}
}
// 获取历史订单记录
void OrderHandler::getOrderHistory(const Request& req, Response& res) {
	// 抓异常
	try {
		// 登录过的用户身份才会有历史记录
		// 认证用户登录状态 获取ID 和 角色
		int userId;
		string role;
		if (!AuthHandler::authenticateRequest(req, userId, role)) {
			return sendError(res, "需要先登录", 401);
		}
		withTransaction([&](DBUtil::Transaction& trans) {
			string sql = "SELECT o.id, o.total_amount, os.name as status, "
                        "o.delivery_address, o.contact_phone, o.created_at "
                        "FROM orders o JOIN order_status os ON o.status_id = os.id "
                        "WHERE o.user_id = " + to_string(userId) + 
                        " ORDER BY o.created_at DESC"; // 根据创建时间降序查询
			// 查询订单
			Value orders = trans.query(sql);
			// 订单详情
			for (auto& order : orders) {
				// 单个订单查询 菜品名 数量 价格
				string itemsSql = "SELECT d.name, or quantity, or.price "
								"FROM order_items or JOIN dishes d ON or.dish_id = d.id "
								"WHERE or.order_id = " + to_string(order["id"].asInt());
				Value items = trans.query(itemsSql);
				order["items"] = items;		// 明细数据加入订单信息
			}
			sendSucess(res, orders);
		});
	} catch (const exception& e) {
		sendError(res, e.what());
	}
}

